#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from spam import spam

import sys
import gobject
import dbus, dbus.mainloop.glib
from dbus import SystemBus, Interface
from dbus.exceptions import DBusException

import logging
logger = logging.getLogger("sms-middleware")
logger.setLevel(logging.DEBUG)
logging.basicConfig(level    = logging.DEBUG,
                    format   = '%(asctime)s %(levelname)s %(message)s',
                    #filename = '/tmp/sms-middleware.log',
                    filename = 'sms-middleware.log',
                    filemode = 'w' )

# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

filter_engine = None

#----------------------------------------------------------------------------#
class DBusObject(object):
#----------------------------------------------------------------------------#
    def __init__(self):
        self.objects = {}
        self.onNewMessage = []
        
        self.framework_obj = None
        
        self.gsm_device_obj = None
        self.gsm_device_iface = None


    def tryGetProxy(self, busname, objname):
        object = None
        try:
            object = self.objects["%s:%s" % (busname, objname)]
        except KeyError:
            try:
                object = self.bus.get_object(busname, objname)
            except DBusException, e:
                logger.warning("could not create proxy for %s:%s" % (busname, objname ))
            else:
                self.objects["%s:%s" % (busname, objname)] = object
        return object

    def initialize(self):
        try:
            dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
            self.mainloop = gobject.MainLoop()
            logger.info("trying to get bus...")
            try:
                self.bus = dbus.SystemBus()
            except Exception, e:
                logger.exception("can't connect to dbus: %s" % e)
            logger.info("ok")

            #self.bus = SystemBus( mainloop=e_dbus.DBusEcoreMainLoop() )
        except DBusException, e:
            logger.exception("could not connect to dbus_object system bus: %s" % e)
            return False

        # Phone
        self.gsm_device_obj = self.tryGetProxy( 'org.freesmartphone.ogsmd', '/org/freesmartphone/GSM/Device' )

        if ( self.gsm_device_obj is not None ) and ( self.gsm_device_iface is None ):
            self.gsm_device_iface = Interface(self.gsm_device_obj, 'org.freesmartphone.GSM.Device')
            self.gsm_network_iface = Interface(self.gsm_device_obj, 'org.freesmartphone.GSM.Network')
            self.gsm_sim_iface = Interface(self.gsm_device_obj, 'org.freesmartphone.GSM.SIM')
            self.gsm_sim_iface.connect_to_signal( "NewMessage", self.cbNewMessage )
            #self.gsm_sim_iface.connect_to_signal( "ReadyStatus", self.cbReadyStatus )
        if self.gsm_device_obj is None:
            logger.error('gsm interface error')
        else:
            logger.info("gsm ok: %s" % self.gsm_network_iface)

        return True

    def cbNewMessage(self, index):
        logger.info('There is a new message int=%s' % (index))
        dbus_object.gsm_sim_iface.RetrieveMessagebook(
            "unread",
            reply_handler=self.cbMessagebookReply,
            error_handler=self.cbMessagebookError
        )
        
        dbus_object.gsm_sim_iface.DeleteMessage(
            index,
            reply_handler=self.cbDeleteMessageReply,
            error_handler=self.cbDeleteMessageError
        )
    
    def cbDeleteMessageReply(self):
        logger.info("message deleted")

    def cbDeleteMessageError(self, e):
        logger.info("message deleting error: %s" % e)
        
    def cbMessagebookReply(self, result):
        logger.info("retrieved messagebook: %s" % result)
        
        for sms in result:
            #print sms
            index, status, sim_number, text = sms[0], sms[1], sms[2], sms[3]
            #is_spam = filter_engine.incoming_sms(sms_ref_number=index, 
                                       #sim_number=sender_number, 
                                       #text=contents)
            is_spam = True
            
            if is_spam == False:
                logger.info('Cool, sms %s is not a spam' % (index))
            elif is_spam == True:
                logger.info('Shit, sms %s is A spam' % (index))

    def cbMessagebookError(self, e):
        logger.error("error while retrieving messagebook %s" % (e))

    def run(self):
        self.mainloop.run()
        
    def quit(self):
        self.mainloop.quit()
             

dbus_object = DBusObject()
dbus_object.initialize()
#filter_engine = spam.SpamEngine()

try:
    dbus_object.run()

except KeyboardInterrupt:
    dbus_object.quit()
    
else:
    logger.info("Normal exit")
    filter_engine.exit()
    sys.exit(0)

